/*
 * Copyright © 2022 XXXXXXXXX
 * @Author: zhangxiang
 * @Date: 2022-06-06 15:03:23
 * @LastEditors: zhangxiang
 * @LastEditTime: 2022-10-10 09:41:44
 * @Description:
 *
 */

import debounce from 'lodash/debounce'

export default {
  data() {
    return {
      $_resizeHandler: null
    }
  },
  computed: {
    /**
     * @description: sidebar重布局
     * @return {*}
     */
    sidebarResize() {
      return this.$store.state.app.sidebar.opened
    }
  },
  watch: {
    /**
     * @description: 监听sidebarResize
     * @param {*} newVal
     * @param {*} oldVal
     * @return {*}
     */
    sidebarResize(newVal, oldVal) {
      setTimeout(() => {
        this.resize()
      }, 300)
    }
  },
  mounted() {
    // 初始化监听器
    this.initListener()
  },
  activated() {
    if (!this.$_resizeHandler) {
      // avoid duplication init
      this.initListener()
    }

    // when keep-alive chart activated, auto resize
    this.resize()
  },
  beforeDestroy() {
    // 销毁监听器
    this.destroyListener()
  },
  deactivated() {
    // 销毁监听器
    this.destroyListener()
  },
  methods: {
    /**
     * @description: 初始化监听器
     * @return {*}
     */
    initListener() {
      this.$_resizeHandler = debounce(() => {
        this.resize()
      }, 100)
      window.addEventListener('resize', this.$_resizeHandler)
    },
    /**
     * @description: 销毁监听器
     * @return {*}
     */
    destroyListener() {
      window.removeEventListener('resize', this.$_resizeHandler)
      this.$_resizeHandler = null
    },
    /**
     * @description: 重布局
     * @return {*}
     */
    resize() {
      const { chart } = this
      chart && chart.resize()
    }
  }
}
